//
//  JQFYTicketInfo_ViewController.m
//  JQFY
//
//  Created by apple on 2017/10/10.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYTicketInfo_ViewController.h"
#import "JQFYTicketInfo_FirstSection.h"
#import "JQFYTickrtInfo_GroupListCell.h"
#import "JQFYTicketInfo_ViewModel.h"
#import "JQFYCreatGroupViewController.h"
#import "JQFYTicketInfoWebViewController.h"
#import "JQFYTicketInfo_GroupListModel.h"
#import "JQFYMessageViewController.h"

typedef void(^groupList)(void);
typedef void(^applyfor)(void);
@interface JQFYTicketInfo_ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *ticketListTab;
@property(nonatomic, strong)JQFYRhythmView *rhythmView;
@property (nonatomic ,copy) NSArray<JQFYTicketInfo_GroupListModel *> *groupListMode;

@end
static NSString *first = @"FirstSation";
static NSString *second = @"SectionSation";

@implementation JQFYTicketInfo_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupTab];
    
    [self getGroupList:^{
        [MBProgressHUD showWithMessage:@"加载成功"];
        NSLog(@"加载成功");
    } failure:^{
        [MBProgressHUD showWithMessage:@"加载失败，网络不好"];
        NSLog(@"加载失败");
    }];
}
//初始化UI
-(void)setupUI{
    UIImage *bgImg = [UIImage imageNamed:@"ticket_info_bg"];
    self.view.layer.contents = (id)bgImg.CGImage;
    UIImage *leftImg = [UIImage imageNamed:@"ticketInfo_back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImg style:UIBarButtonItemStylePlain target:self action:@selector(didClickBack)];
    UIView *titView = [[UIView alloc] initWithFrame:CGRectMake(35, 0, 300, 40)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:titView.bounds];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:15];
    titleLabel.text = self.model.tickets_title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titView addSubview:titleLabel];
    self.navigationItem.titleView = titView;
}
//setupUI
-(void) setupTab{
    self.ticketListTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_ticketListTab];
    [_ticketListTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(self.view);
        make.leading.mas_equalTo(self.view).mas_offset(15 *SCAL);
        make.trailing.mas_equalTo(self.view).mas_offset(-15 *SCAL);
    }];
    _ticketListTab.delegate = self;
    _ticketListTab.dataSource = self;
    [_ticketListTab registerClass:[JQFYTicketInfo_FirstSection class] forCellReuseIdentifier: first];//注册
    [_ticketListTab registerClass:[JQFYTickrtInfo_GroupListCell class] forCellReuseIdentifier: second];//注册
    _ticketListTab.backgroundColor = [UIColor clearColor];
    _ticketListTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _ticketListTab.showsVerticalScrollIndicator = NO;
    _ticketListTab.tableHeaderView.userInteractionEnabled = YES;
    [self setupHeaderView];//设置组头
}
//设置组头
-(void)setupHeaderView
{
    //设置组头
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _ticketListTab.bounds.size.width, 300 *SCAL)];
    headerView.backgroundColor = [UIColor clearColor];
    [_ticketListTab setTableHeaderView:headerView];
    UIImageView *ImgView = [[UIImageView alloc] init];
    ImgView.userInteractionEnabled = YES;
    [headerView addSubview:ImgView];
    [ImgView setBackgroundColor:[UIColor whiteColor]];
    [ImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(headerView);
        make.bottom.mas_equalTo(headerView).offset(-15 *SCAL);
        make.top.mas_equalTo(headerView).offset(15 *SCAL);
    }];
    UIView *iconBgView = [[UIView alloc] init];
    [ImgView addSubview:iconBgView];
    [iconBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.mas_equalTo(ImgView).mas_offset(5 *SCAL);
        make.bottom.trailing.mas_equalTo(ImgView).mas_offset(-5 *SCAL);
    }];
    iconBgView.clipsToBounds = YES;
    UIImageView *iconImg = [[UIImageView alloc] init];
    [iconBgView addSubview:iconImg];
    [iconImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(iconBgView);
        make.bottom.mas_equalTo(ImgView).mas_offset(120 *SCAL);
    }];
    [iconImg sd_setImageWithURL:[NSURL URLWithString:self.model.tickets_cover] placeholderImage:[UIImage imageNamed:@"ticket_info_headerBtn"]];
    iconImg.userInteractionEnabled = YES;
    UIImageView *coverImg = [[UIImageView alloc] init];
    [iconImg addSubview:coverImg];
    [coverImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.mas_equalTo(ImgView).mas_offset(5 *SCAL);
        make.bottom.trailing.mas_equalTo(ImgView).mas_offset(-5 *SCAL);
    }];
    coverImg.userInteractionEnabled = YES;
    [coverImg setImage:[UIImage imageNamed:@"ticket_info_cover"]];
    UIImageView *moreImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ticket_info_more"]];
    [coverImg addSubview:moreImg];
    [moreImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(coverImg);
        make.bottom.mas_equalTo(coverImg.mas_bottom).offset(-10 *SCAL);
        make.height.mas_offset(20 *SCAL);
        make.width.mas_offset(85 *SCAL);
    }];
    UILabel *nameLabel = [[UILabel alloc] init];
    [coverImg addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(coverImg).offset(15);
        make.trailing.mas_equalTo(coverImg).offset(-15);
        make.bottom.mas_equalTo(moreImg.mas_top).mas_offset(-10 *SCAL);
    }];
    nameLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:15 *SCAL];
    nameLabel.textColor = [UIColor lightGrayColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.numberOfLines = 2;
    nameLabel.text = self.model.tickets_title?self.model.tickets_title:@"2017 UNINHIBITED NIGTH";
    //添加手势
    UITapGestureRecognizer *headerGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerTap)];
    [coverImg addGestureRecognizer:headerGesture];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *hView = [[UIView alloc] init];
        hView.backgroundColor = [UIColor clearColor];
        UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ticket_info_ChatGroup"]];
        [hView addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.leading.mas_equalTo(hView);
            make.height.mas_offset(13 *SCAL);
            make.width.mas_offset(75 *SCAL);
        }];
        return hView;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100 *SCAL;
    }else{
        return 85 *SCAL;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 25 *SCAL;
    }else{
        return 0;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }else{
        return self.groupListMode.count?self.groupListMode.count:1;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        JQFYTicketInfo_FirstSection *cell = [tableView dequeueReusableCellWithIdentifier:first forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setCellImage:indexPath.row];
        return cell;
    }else{
        JQFYTickrtInfo_GroupListCell *cell = [tableView dequeueReusableCellWithIdentifier:second forIndexPath:indexPath];
        cell.model = self.groupListMode[indexPath.row];
        cell.avtivity_Name = self.model.tickets_title;//赋值活动名称
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了第%ld组第%ld行",(long)indexPath.section,(long)indexPath.row);
//    if (indexPath.section == 0 & indexPath.row == 0) {
//        JQFYCreatGroupViewController *creatGruop = [[JQFYCreatGroupViewController alloc] init];
//        creatGruop.Listmodel = self.model;
//        [self.navigationController pushViewController:creatGruop animated:YES];
//    }
//    if (indexPath.section == 1 ) {
//        [self applyforGroupWith:indexPath.row :^{
//            [MBProgressHUD showWithMessage:@"申请成功"];
//            NSLog(@"申请成功")
//            
//        } failure:^{
//            [MBProgressHUD showWithMessage:@"申请失败"];
//        }];
//    }
    [MBProgressHUD showWithMessage:@"该功能尚未开放"];
}

#pragma mark -
#pragma mark 点击事件
//组头手势
-(void)headerTap{
    NSLog(@"点击了组头");
    JQFYTicketInfoWebViewController *ticketWebVc = [[JQFYTicketInfoWebViewController alloc]init];
    ticketWebVc.model = self.model;
    [self.navigationController pushViewController:ticketWebVc animated:YES];
}
//点击返回键
-(void)didClickBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 网络请求
//活动群
-(void) getGroupList:(groupList)success failure:(groupList)failure{
    NSDictionary *dic = @{
                          @"activeid":self.model.id,
                          @"token":[JQFYUserData userDataInSandbox].token
                          };
    [[JQFYNetworkTool sharedManager] request:RequestMethodPost urlString:@"http://app.uninhibited.cn/api/easemob/ticket/group/list" parameters:dic finished:^(id responseObject, NSError *error) {
        if (error) {
            failure();
            NSLog(@"--%@",error);
        }else{
            success();
            NSArray *listArray = responseObject;
            if (listArray && [listArray isKindOfClass:[NSArray class]]) {
                _groupListMode = [NSArray yy_modelArrayWithClass:[JQFYTicketInfo_GroupListModel class] json:listArray];
                [self.ticketListTab reloadData];
            }
        }
    }];
}
//请求加入群
-(void) applyforGroupWith:(NSInteger)Index :(applyfor)success failure:(applyfor)failure{
    NSString *groupId = self.groupListMode[Index].group_easemob_id;
    NSString *userId = self.groupListMode[Index].group_owner_user;
    NSDictionary *dic = @{
                          @"group_id":groupId,
                          @"users_id":userId,
                          @"token":[JQFYUserData userDataInSandbox].token
                          };
    [[JQFYNetworkTool sharedManager] request:RequestMethodPost urlString:@"http://app.uninhibited.cn/api/easemob/apply/group/add" parameters:dic finished:^(id responseObject, NSError *error) {
        if (error) {
            failure();
            NSLog(@"--%@",error);
        }else{
            success();
            
//            [[EMClient sharedClient].chatManager getConversation:groupId type:EMConversationTypeGroupChat createIfNotExist:YES];
//            EMError *error = nil;
//            [[EMClient sharedClient].groupManager joinPublicGroup:groupId error:&error];
//            JQFYMessageViewController *chatController = [[JQFYMessageViewController alloc] initWithConversationChatter:groupId conversationType:EMConversationTypeGroupChat];
//            [self.navigationController pushViewController:chatController animated:YES];
        }
    }];

}
@end
